<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/09
 * Time: 09:00
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\ProductCategory;
use app\common\service\product\ProductService;
use think\facade\Cache;
use think\facade\Validate;

class CategoryController extends BaseController
{
    /**
     * 树形缓存下标
     * @var string
     */
    protected $cacheTree = "category-build-tree";

    /**
     * 分类列表
     * @return string|string[]
     * @date 2020/09/14
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $cates = ProductCategory::select()->toArray();
            $list = Tools::generateTree($cates, 'cate_id', 'parent_id');
            $list = Tools::levelArray($list);
            $this->assign("list", $list);
            return $this->fetch('lists');
        }
        return $this->fetch("index");
    }

    /**
     * 更新分类信息
     * @date 2020/09/14
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'parent_id'  => 'require',
                'name' => 'require'
            ],[
                'parent_id.require' => '父类必选',
                'name.require' => '名称必填',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductCategory::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'cate_id'  => 'require',
            ],[
                'cate_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['cate_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        Cache::rm($this->cacheTree);
        ProductService::getInstance()->addCategory($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 添加分类
     * @date 2020/09/14
     * @author longli
     */
    public function add()
    {
        $cates = ProductCategory::order("parent_id")->select()->toArray();
        $cates = Tools::generateTree($cates, 'cate_id', 'parent_id');
        $cates = Tools::levelArray($cates);
        $this->assign("category", $cates);
        $cateId = $this->request->get("cate_id");
        if(!empty($cateId)) $this->assign("cate", ProductCategory::get($cateId));
        return $this->fetch("add");
    }

    /**
     * 删除分类
     * @date 2020/09/14
     * @author longli
     */
    public function delete()
    {
        $cateId = $this->request->request("ids");
        if(empty($cateId)) $this->error('参数错误');
        ProductCategory::destroy($cateId);
        $this->success('删除成功');
    }

    /**
     * 获取子类
     * @date 2020/09/09
     * @author longli
     */
    public function category()
    {
        $cateId = $this->request->get("cate_id");
        if(empty($cateId)) $this->error('参数错误');
        $this->success('获取成功', '', ProductCategory::getByPid($cateId));
    }


    /**
     * 获取分类树形
     * @date 2020/09/13
     * @author longli
     */
    public function getTree()
    {
        $cateId = $this->request->get("cate_id", 0, 'intval');
        $tree = Cache::remember($this->cacheTree, function()use($cateId)
        {
            $tree = ProductCategory::buildTree(true);
            return Tools::replaceArrayKey(['cate_id' => 'id', 'son' => 'children', 'name' => 'title'], $tree);
        });
        self::addStyleTree($tree, $cateId);
        $tree = Tools::arrayValues($tree, false);
        return apiResponse(\app\common\status\BaseStatus::CODE_NORMAL, $tree, '获取成功');
    }

    /**
     * 分类树形添加展开收缩样式
     * @param array $tree buildTree 生成数据
     * @param int|int[] $selectId 默认展开的id
     * @date 2020/09/13
     * @author longli
     */
    public static function addStyleTree(& $tree, $selectId = 0)
    {
        if($selectId < 1) return;
        $all = ProductCategory::getParentAll($selectId);
        if(isset($tree[$all[0]['cate_id']]))
        {
            if(count($all) == 1)
            {
                $tree[$all[0]['cate_id']] += ["spread" => true];
            }
            else
            {
                $tree[$all[0]['cate_id']] += ["spread" => true];
                $tree[$all[0]['cate_id']]['children'][$all[1]['cate_id']] += ["spread" => true];
            }
        }
    }
}